package server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import server.auth.AuthManager;
import server.auth.SimpleAuthManager;
import server.stackMachine.IntegerStackMachineControler;

public class NewConnectionHandler extends Thread {

	private static final AuthManager AUTH = new SimpleAuthManager();
	private ServerSocket serverSocket;
	private Socket socket;

	public NewConnectionHandler(ServerSocket ss, Socket s) {
		this.socket = s;
		this.serverSocket = ss;
	}

	private void doIt() throws IOException {
		BufferedReader reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
		PrintWriter writer = new PrintWriter(this.socket.getOutputStream());
		
		if (!AUTH.auth(reader)) {
			writer.println("incorrect username or password");
			writer.flush();
			writer.close();
			reader.close();
			this.socket.close();
			return;
		}
		
		while(!this.socket.isClosed()) {
			String s = reader.readLine();
			if (s.compareToIgnoreCase("trap 0,halt,0") == 0) {
				writer.println("terminating service");
				writer.flush();
				this.serverSocket.close();
				writer.close();
				reader.close();
				this.socket.close();
			} else if(s.compareToIgnoreCase("exit") == 0) {
				writer.println("bye");
				writer.flush();
				writer.close();
				reader.close();
				this.socket.close();
			} else if (s.compareToIgnoreCase("touppercase") == 0) {
				String t = reader.readLine();
				writer.println(t.toUpperCase());
				writer.flush();
			} else if (s.compareToIgnoreCase("IntStackMachine") == 0) {
				new IntegerStackMachineControler(this.socket, reader, writer).control();
			} else {
				writer.println("unkown command");
				writer.flush();
			}
		}
	}

	@Override
	public void run() {
		try {
			doIt();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

}
